package com.zby.lease.web.admin.service.imp;


import com.zby.lease.common.minio.MinioProperties;
import com.zby.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;


    @Override
    public String

        upload(MultipartFile file) {
        try {
            boolean b = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());

            if (!b){
//                 创建存储桶
                minioClient.makeBucket(MakeBucketArgs
                        .builder()
                        .bucket(minioProperties.getBucketName())
                        .build());
                //             设置桶的读写权限
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder()
                                .bucket(minioProperties.getBucketName())
                                .config(createBucketPolicyConfig(minioProperties.getBucketName()))
                                .build()
                );

            }
            // 先生成日期部分
            String datePart = new SimpleDateFormat("yyyyMMdd").format(new Date());
// 然后拼接完整的文件名
            String fileName = datePart + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//            String fileName =  new SimpleDateFormat("yyyyMMdd")
//                    .format(new Date()+"/"+ UUID.randomUUID()+"-"+file.getOriginalFilename());
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build());
                System.out.println(file.getContentType());
                return  String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);
        }catch (Exception e){
             e.printStackTrace();

        }
        return null;
    }
    private String createBucketPolicyConfig(String bucketName) {
        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}
